package com.hw.job_4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {

    public static void main(String[] args) {

        ServerSocket ss = null;
        Socket s = null;
        BufferedReader bf = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            ss = new ServerSocket(8888);
            System.out.println("等待客户端的连接中...");
            s = ss.accept();
            System.out.println("客户端 " + s.getInetAddress() + "连接成功");

            oos = new ObjectOutputStream(s.getOutputStream());
            ois = new ObjectInputStream(s.getInputStream());
            while (true) {
                Object obj = ois.readObject();
                if (obj instanceof UserMessage) {
                    UserMessage um = (UserMessage)obj;
                    System.out.println("服务端获取到的信息是：" + um);

                    String userName = um.getUser().getUserName();
                    String pwd = um.getUser().getPwd();
                    if (userName.equals("admin") && pwd.equals("123456")) {
                        um.setType("success");
                    } else {
                        um.setType("fail");
                    }
                    oos.writeObject(um);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != ss) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != bf) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
